/*例9-7 通过poll调用实现网络服务器和客户端的功能*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <limits.h>

#define MAXLINE 10240

#ifndef OPEN_MAX
#define OPEN_MAX 40960
#endif

void handle(struct pollfd clients[], int maxclient, int readyclient);

int main(int argc, char** argv) {
    int servPort = 6888;
    int listenq = 1024;
    int listenfd, connfd;
    struct pollfd clients[OPEN_MAX];
    int maxi;
    socklen_t socklen = sizeof(struct sockaddr_in);
    struct sockaddr_in cliaddr, servaddr;
    char buf[MAXLINE];
    int nready;

    // 修正1：初始化整个 servaddr 结构体
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(servPort);

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1) {
        perror("socket error");
        exit(-1);
    }

    int opt = 1;
    if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        perror("setsockopt error");
        exit(-1);
    }

    if (bind(listenfd, (struct sockaddr*)&servaddr, socklen) == -1) {
        perror("bind error");
        exit(-1);
    }

    if (listen(listenfd, listenq) == -1) {
        perror("listen error");
        exit(-1);
    }

    clients[0].fd = listenfd;
    clients[0].events = POLLIN;

    for (int i = 1; i < OPEN_MAX; i++) {
        clients[i].fd = -1;
    }

    maxi = 0;
    printf("poll echo server startup, listen on port:%d\n", servPort);
    printf("max connection is:%d\n", OPEN_MAX);

    for (;;) {
        nready = poll(clients, maxi + 1, -1);
        if (nready == -1) {
            perror("poll error");
            exit(-1);
        }

        if (clients[0].revents & POLLIN) {
            connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &socklen);
            sprintf(buf, "accept from %s:%d\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));  // 修正端口打印
            printf("%s", buf);

            int i;  // 修正2：声明在循环外
            for (i = 1; i < OPEN_MAX; i++) {
                if (clients[i].fd == -1) {
                    clients[i].fd = connfd;
                    clients[i].events = POLLIN;
                    if (i > maxi) {
                        maxi = i;
                    }
                    --nready;
                    break;
                }
            }

            // 修正3：检查索引是否越界
            if (i >= OPEN_MAX) {
                printf("too many connections\n");
                close(connfd);
                continue;
            }
        }

        handle(clients, maxi, nready);
    }

    return 0;
}

void handle(struct pollfd clients[], int maxclient, int nready) {
    int connfd;
    int i, nread;
    char buf[MAXLINE];

    if (nready == 0) {
        return;
    }

    for (i = 1; i <= maxclient; i++) {  // 修正4：循环条件应为 i <= maxclient
        connfd = clients[i].fd;
        if (connfd == -1) {
            continue;
        }

        if (clients[i].revents & (POLLIN | POLLERR)) {
            nread = read(connfd, buf, MAXLINE);
            if (nread < 0) {
                perror("read error");
                close(connfd);
                clients[i].fd = -1;
                continue;
            }

            if (nread == 0) {
                printf("client close the connection\n");
                close(connfd);
                clients[i].fd = -1;
                continue;
            }

            buf[nread] = '\0';
            printf("server received data is:%s\n", buf);

            // 修正5：回显数据给客户端
            if (write(connfd, buf, nread) < 0) {
                perror("write error");
            }

            --nready;
            if (nready <= 0) {
                break;
            }
        }
    }
}
